import argparse
import codecs
import logging
import os
import os.path as osp
import sys

from termcolor import colored
from qtpy import QtCore
from qtpy import QtWidgets

from .utils import newIcon
from .utils import read_yaml
from returnlabels import __appname__
from returnlabels import __version__
from returnlabels.app import MainWindow

here = osp.dirname(osp.abspath(__file__))


def main():
    perser = argparse.ArgumentParser()
    perser.add_argument("--config", 
                        default=argparse.SUPPRESS, 
                        type=str, 
                        help="")
    args = perser.parse_args()
    print("===> args: ", args)

    config_path = osp.join(here, "configs", "default.yml")
    if hasattr(args, "config"):
        if osp.isfile(args.config) and osp.basename(args.config).split(".")[-1]=="yml":
            config_path = args.config
            print("===> Use input config: ", config_path)
    else:
        print("===> Use default config: ", config_path)
    
    config = read_yaml(config_path)
    if "headers" in config:
        headers = config["headers"]
    else:
        print(f"===> {colored('ERROR:', 'red')} config files not set 'headers'")
        sys.exit()
    
    if "url_dict" in config:
        url_dict = config["url_dict"]
    else:
        print(f"===> {colored('ERROR:', 'red')} config files not set 'url_dict'")
        sys.exit()
    
    if "project_dict" in config:
        project_dict = config["project_dict"]
    else:
        print(f"===> {colored('ERROR:', 'red')} config files not set 'project_dict'")
        sys.exit()

    translator = QtCore.QTranslator()
    translator.load(
        QtCore.QLocale.system().name(),
        osp.join(here, "translate"),
    )
    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName(__appname__) # 应用名称
    app.setWindowIcon(newIcon("logo"))  # Icon
    app.installTranslator(translator)   # 语言转换

    win = MainWindow(
        headers=headers,
        url_dict=url_dict,
        project_dict=project_dict,
    )
    win.show()
    win.raise_()
    sys.exit(app.exec_())


# this main block is required to generate executable by pyinstaller
if __name__ == "__main__":
    main()
